package dyyx.client.echo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

// ByteBuf
public class EchoClientHandler extends SimpleChannelInboundHandler<Object> {

	@Override
	public void channelActive(ChannelHandlerContext ctx) {

		// 注意一定要加 \n !!!
		// ctx.writeAndFlush(Unpooled.copiedBuffer("client-msg at " + new Date() + "\n", StandardCharsets.UTF_8));
		
		// ctx.writeAndFlush("client-msg at " + new Date() + "\n");
	}

	@Override
	public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

		// 加上 编码解码器后  msg 为 string 类型
		// received:PooledUnsafeDirectByteBuf(ridx: 0, widx: 43, cap: 1024)
		System.out.println("received:" + msg);
		
		
		/*
		ByteBuf buf = null;
		try {
			buf = (ByteBuf) msg;
			// 创建目标大小的数组
			byte[] bytes = new byte[buf.readableBytes()];
			// 把数据从bytebuf转移到byte[]
			buf.getBytes(0, bytes);
			System.out.println(new String(bytes));
			// buf.release();
		} finally {
			// ERROR:io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1

			// if (buf != null) {
			// 	buf.release();
			// }
		}
		*/
	
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

		System.out.println("ERROR:" + cause);
		ctx.close();
	}

}
